﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AMS.DD35.WebMVP.Presenters;
using AMS.DD35.WebMVP.Models;
using AMS.Core.Services;
using AMS.DD35.WcfConnector;
using AMS.DD35.WebMVP.State;

namespace AMS.DD35.WebMVP.Views
{
    public partial class LoginView : System.Web.UI.Page, ILoginView
    {
        LoginPresenter _presenter;

        public string UserName
        {
            get { return txtUserName.Text; }
            set { txtUserName.Text = value; }
        }

        public string Password
        {
            get { return txtPassword.Text; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            ILoginService login = new LoginProxy();
            AMS.DD35.WebMVP.State.IStateManager state = new StateManager();
            ILoginModel model =  new LoginModel(login, state);
            _presenter = new LoginPresenter(this, model);

            // hook up events
            model.LoginFailed += new EventHandler(HandleLoginFailed);
            model.LoginSucceeded += new EventHandler(HandleLoginSucceeded);
        }

        // protected event handlers enable in-script hook-up
        protected void HandleLoginButton_Click(object sender, EventArgs args)
        {
            _presenter.Login();
        }

        protected void HandleLoginSucceeded(object sender, EventArgs args)
        {
            // redirect to CharactersView
            //string rootDir = ConfigurationManager.AppSettings[Constants.uriRootDir];
            //if (!rootDir.EndsWith("/"))
            //    rootDir = string.Format("{0}/", rootDir);

            //Response.Redirect(rootDir + ConfigurationManager.AppSettings[Constants.uriCharacters]);

            //Response.Redirect("CharactersView.aspx");
            //throws System.Threading.ThreadAbortException by design?!
            //http://support.microsoft.com/kb/312629/en-us 
            Response.Redirect("CharactersView.aspx", false);

        }

        protected void HandleLoginFailed(object sender, EventArgs args)
        {
            lblLoginFailure.Text = "Incorrect username or password";
        }
    }
}
